package com.yunchang.spring.visitor.demo.handler;

import com.yunchang.spring.visitor.core.handler.response.IResponseHandler;
import com.yunchang.spring.visitor.core.utils.WebUtil;
import com.yunchang.spring.visitor.demo.utils.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 自定义返回处理器示例：统一以Map形式返回httpResponse
 * Created by tujun on 2018/1/16.
 */
@Component
public class MyResponseHandler implements IResponseHandler {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());


    @Override
    public Object handleResponse(HttpServletRequest request, HttpServletResponse response,
                                 String service, String method, long costTime, Object result,
                                 Map<String, String> params, String httpContent) {
        // 统一返回内容为json格式，成功status为ok，失败status为fail
        Map<String, Object> resMap = new HashMap<String, Object>();
        resMap.put("status", "ok");
        if (result instanceof Map) {
            resMap.putAll((Map<? extends String, ?>) result);
        } else {
            resMap.put("result", result);
        }
//        if (logger.isInfoEnabled()) {
            Map<String, Object> logMap = new HashMap<String, Object>();
            logMap.put("time", System.currentTimeMillis());
            logMap.put("cost", costTime);
            logMap.put("uri", WebUtil.getUri(request));
            logMap.put("ip", WebUtil.getIpAddr(request));
            logMap.put("method", service + "." + method);
            logMap.put("params", params);
            logMap.put("httpContent", httpContent);
            logMap.put("response", resMap);
//            logger.info(JsonUtil.toJson(logMap));
            System.out.println(JsonUtil.toJson(logMap));
//        }
        response.setHeader("Connection", "close");
        response.setContentType("application/json;charset=UTF-8");
        return resMap;
    }
}
